/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.entity.Client;
import ejb.entity.Compte;
import ejb.entity.Operations;
import ejb.entity.OperationsBatch;
import ejb.facade.ClientFacadeRemote;
import ejb.facade.CompteFacadeRemote;
import ejb.facade.OperationsFacadeRemote;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author chulin
 */
@WebServlet(name = "AjouterOperationBatch", urlPatterns = {"/AjouterOperationBatch"})
public class AjouterOperationBatch extends HttpServlet {

    @EJB
    private ClientFacadeRemote clientFacade;
    @EJB
    private OperationsFacadeRemote operationsFacade;
    @EJB
    private CompteFacadeRemote compteFacade;
    @Resource(mappedName = "jms/NewOperationMessageFactory")
    private ConnectionFactory operationConnectionFactory;
    @Resource(mappedName = "jms/NewOperationMessage")
    private Queue operationQueue;
    @Resource(mappedName = "jms/NewOperationBatchMessageFactory")
    private ConnectionFactory operationBatchConnectionFactory;
    @Resource(mappedName = "jms/NewOperationBatchMessage")
    private Queue operationBatchQueue;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        Integer id_compte_source = Integer.valueOf(request.getParameter("id_compte_source"));
        Integer id_compte_cible = null;
        if (request.getParameter("id_compte_cible") != null && !"".equals(request.getParameter("id_compte_cible"))) {
            id_compte_cible = Integer.valueOf(request.getParameter("id_compte_cible"));
        }
        String type_operation = request.getParameter("type_operation");
        Integer montant = null;
        if (request.getParameter("montant") != null) {
            montant = Integer.valueOf(request.getParameter("montant"));
        }
        if ((id_compte_source != null) && (type_operation != null) && (montant != null)) {
            try {
                Connection connection = operationConnectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageProducer messageProducer = session.createProducer(operationQueue);
                ObjectMessage message = session.createObjectMessage();

                Compte compte_source = compteFacade.find(id_compte_source);
                Compte compte_cible = null;
                if (id_compte_cible != null) {
                    compte_cible = compteFacade.find(id_compte_cible);
                }

                Operations e = new Operations();
                e.setTypeOperation(type_operation);
                e.setDateDeCreation(new Date());
                e.setIdCompteSource(id_compte_source);
                e.setIdCompteCible(id_compte_cible);
                e.setMontant(montant);

                Operations eLast = operationsFacade.findLast();

                message.setObject(e);
                messageProducer.send(message);
                messageProducer.close();
                session.close();
                connection.close();

                connection = operationBatchConnectionFactory.createConnection();
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                messageProducer = session.createProducer(operationBatchQueue);
                message = session.createObjectMessage();

                OperationsBatch e2 = new OperationsBatch();
                e2.setIdOperation(eLast.getIdOperation() + 1);

                message.setObject(e2);
                messageProducer.send(message);
                messageProducer.close();
                session.close();
                connection.close();

                response.sendRedirect("ListClient");
            } catch (JMSException ex) {
                ex.printStackTrace();
            }
        }

        PrintWriter out = response.getWriter();
        try {
            Compte compte_source = compteFacade.find(id_compte_source);
            Client client = clientFacade.find(compte_source.getIdClient());
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet AjouterOperation</title>");
            out.println("<script type='text/javascript' src='script/javascript.js'></script>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Effectuer une operation batch sur " + compte_source.getTypeCompte() + " N° " + compte_source.getIdCompte() + "</h1>");
            out.println("<form>");
            out.println("Type d'opération : <select id='type_operation' name='type_operation' onchange='typeOperation();'>");
            out.println("<option>Retrait</option>");
            out.println("<option>Credit</option>");
            if (client.getNombreCompte() > 1) {
                out.println("<option>Virement</option>");
            }
            out.println("</select><br/>");
            if (client.getNombreCompte() > 1) {
                out.println("<span id='cpt_dest' style='display:none'>");
                out.println("Compte destinataire : <select id='id_compte_cible' name='id_compte_cible'>");
                out.println("<option value=''></option>");
                for (Compte compte : compteFacade.findAll(compte_source.getIdClient())) {
                    if (compte.getIdCompte().equals(compte_source.getIdCompte())) {
                        continue;
                    }
                    out.println("<option value=");
                    out.println(compte.getIdCompte());
                    out.println(">");
                    out.println(compte.getTypeCompte() + " N° " + compte.getIdCompte());
                    out.println("</option>");
                }
                out.println("</select>");
                out.println("</span>");
            }
            out.println("Montant : <input type='number' id='montant' name='montant' value='1' min='0' max='" + compte_source.getSolde() + "'><br/>");
            out.println("<input type='hidden' name='id_compte_source' value='" + id_compte_source + "'>");
            out.println("<input type='hidden' id='montant_max' name='montant_max' value='" + compte_source.getSolde() + "'>");
            out.println("<input type='submit'><br/>");
            out.println("</form>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
